CREATE PROCEDURE RRHH_REGISTRAR_ASISTENCIA_L
@IDLOGIN VARCHAR(20),
@FECHA DATETIME,
@ESTADOTRAN INTEGER OUTPUT
AS

--SET TRANSACTION ISOLATION LEVEL SERIALIZABLE

BEGIN TRANSACTION

DECLARE @IDEMP INTEGER
DECLARE @IDASI INTEGER
DECLARE @IDUSU INTEGER
DECLARE @CONT INTEGER
DECLARE @AUXDIA1 DATETIME
DECLARE @AUXDIA2 DATETIME
DECLARE @FEC DATETIME

BEGIN TRY
	SET @IDUSU = (SELECT IDUSUARIO FROM USUARIO WHERE USERNAME = @IDLOGIN)
	SET @IDEMP = (SELECT IDEMPLEADO FROM EMPLEADO WHERE IDUSUARIO = @IDUSU)
	
	SET @CONT = (SELECT COUNT(*) FROM AGENDADIARIA
				 WHERE CAST(fecha AS DATE) = CAST(@FECHA AS DATE) AND
				 @IDEMP = idEmpleado)
				 
	IF @CONT = 0
	BEGIN
		INSERT INTO AGENDADIARIA (fecha, idEmpleado)
		VALUES (@FECHA, @IDEMP)
	END
	
	SET @IDASI = (SELECT MAX(IDASISTENCIADIARIA) FROM ASISTENCIADIARIA
				  WHERE CAST(fecha AS DATE) = CAST(@FECHA AS DATE) AND
				 @IDEMP = idEmpleado)
	
	IF @IDASI IS NULL
	BEGIN
		SET @FEC = (SELECT FECHA FROM AGENDADIARIA
					WHERE CAST(fecha AS DATE) = CAST(@FECHA AS DATE) AND
					@IDEMP = idEmpleado)
		
		INSERT INTO ASISTENCIADIARIA (IDASISTENCIADIARIA, fecha, idEmpleado, 
		horaEntrada, horaSalida)
		VALUES (1, @FEC, @IDEMP, CAST(@FECHA AS TIME(7)), NULL)
		
		SET @ESTADOTRAN = 1
		COMMIT TRANSACTION
	END
	ELSE
	BEGIN
		SET @AUXDIA1 = (SELECT HORAENTRADA FROM ASISTENCIADIARIA
					   WHERE @IDASI = IDASISTENCIADIARIA AND
					   CAST(fecha AS DATE) = CAST(@FECHA AS DATE) AND
					   @IDEMP = idEmpleado)
		SET @AUXDIA2 = (SELECT HORASALIDA FROM ASISTENCIADIARIA
					   WHERE @IDASI = IDASISTENCIADIARIA AND
					   CAST(fecha AS DATE) = CAST(@FECHA AS DATE) AND
					   @IDEMP = idEmpleado)
		
		IF (@AUXDIA2 IS NULL)	   
		BEGIN
			UPDATE ASISTENCIADIARIA
			SET HORASALIDA = (CAST(@FECHA AS TIME(7)))
			WHERE @IDASI = IDASISTENCIADIARIA AND
				  CAST(fecha AS DATE) = CAST(@FECHA AS DATE) AND
				  @IDEMP = idEmpleado
				  
			SET @ESTADOTRAN = 2
			COMMIT TRANSACTION
		END
		ELSE
		IF (@AUXDIA2 IS NOT NULL) AND (@AUXDIA1 IS NOT NULL)
		BEGIN
			SET @IDASI = @IDASI + 1
			
			SET @FEC = (SELECT FECHA FROM AGENDADIARIA
						WHERE CAST(fecha AS DATE) = CAST(@FECHA AS DATE) AND
						@IDEMP = idEmpleado)
					
			INSERT INTO ASISTENCIADIARIA (IDASISTENCIADIARIA, fecha, idEmpleado, 
			horaEntrada, horaSalida)
			VALUES (@IDASI, @FEC, @IDEMP, CAST(@FECHA AS TIME(7)), NULL)
			
			SET @ESTADOTRAN = 1
			COMMIT TRANSACTION
		END
	END
END TRY
BEGIN CATCH
	SET @ESTADOTRAN = 0
	ROLLBACK TRANSACTION
END CATCH